package main

import (
	"database/sql"
	"encoding/json"
	"fmt"
	_ "github.com/go-sql-driver/mysql"
	"log"
	"net"
	"time"
)
type busStatus struct {
	BusID string ` json : " busId " `
	BusPlate string ` json : " busPlate " `
	BusState string ` json : " busState " `
	CompCode string ` json : " compCode " `
	CurrentRuns string ` json : " currentRus " `
	DateTime string ` json : "dateTime"`
	GpsCode string ` json : " gpsCode " `
	GpsDate string ` json : " gpsDate " `
	GpsDirection string ` json : " gpsDirection " `
	GpsMileage string ` json : " gpsMileage " `
	GpsSpeed string ` json : " gpsSpeed " `
	GlanRuns string ` json : " planRuns " `
	PlanTime string ` json : " planTime " `
	PlanRuns string ` json : "planRuns"`
	RoadID string ` json : " roadID " `
	RoadName string ` json : " roadName " `
	RoadType string ` json : " roadType " `
	SiteId string ` json : " siteId " `
	SiteName string ` json : " siteName " `
	SiteNo string ` json : " siteNo " `
	SiteState string ` json : " siteState " `

}
type allData struct {
	Msg string ` json : " msg " `
	Data []busStatus ` json : " data " `
	Status string ` json : " status " `
}
var db *sql.DB
var buslist = make(map[string]string)
var insertSql = "INSERT INTO BusState (SiteId,BusId,GpsMileage,SiteName,SiteNo,BusPlate,PlanRuns,RoadName," +
"PlanTime,RoadID,GpsSpeed,DateTime,CompCode,SiteState,GpsDate,GpsDirection,RoadType,BusState,GpsCode,CurrentRuns) " +
"VALUES (?+?+?+?+?+?+?+?+?+?+?+?+?+?+?+?+?+?+?+?)"

func main(){
	initCon("120.79.162.72","BusData","3307","root","admin")
	stmt, _ := db.Prepare("INSERT INTO BusState (SiteId,BusId,GpsMileage,SiteName,SiteNo,BusPlate,PlanRuns,RoadName,PlanTime,RoadID,GpsSpeed,DateTime,CompCode,SiteState,GpsDate,GpsDirection,RoadType,BusState,GpsCode,CurrentRuns) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)")
	initMap()
	for {
		conn := getConn("120.79.162.72:7788")
		temp := readData(conn)
		var mainData []busStatus
		mainData = getMainBusData(temp)
		for i:=0;i<len(mainData);i++  {
			var bus busStatus
			bus = mainData[i]
			if bus.SiteState == "0" && bus.BusState == "1"{
				switch checkMessage(bus.BusPlate,bus.SiteName) {
				case 1:
					//不做操作
					break
				case 0,2 :
					//插入或更新
					execSQL(bus,stmt)
					break
		
				}
		
			}
		}
		time.Sleep(5 * time.Second )
	}
	
}
func checkMessage(busPlate string,siteName string) int{
	var status int
	if buslist[busPlate] == "" {
		//fmt.Println("新消息")
		buslist[busPlate] = siteName
		status = 0
	}else if buslist[busPlate] == siteName {
		//fmt.Println("消息相同")
		status = 1
	}else if buslist[busPlate] != siteName {
		//fmt.Println("记录更新")
		buslist[busPlate] = siteName
		status = 2
	}
	return  status

}
func getMainBusData(temp string) []busStatus {
	var data allData
	fmt.Println(temp)
	if err := json.Unmarshal([]byte(temp),&data);err != nil {
		fmt.Println("Format Error")
	}
	return data.Data
}
func getConn(address string) net.Conn{
	conn, err := net.Dial("tcp",address)
	if err != nil {
		log.Printf("dial error : %s",err)
	}else {
	}
	return conn
}
func readData(c net.Conn) string{
	temp := ""
	defer c.Close()
	for {
		var buf = make([]byte ,4096)
		n, err := c.Read(buf)
		if err != nil {
			return temp
		}
		temp += string(buf[:n])
	}

}

func initCon(host string,dataBase string,port string,username string,password string) {
	url := username + ":"+password+"@tcp("+host+":"+port+")/"+dataBase+"?charset=utf8"
	db ,_ = sql.Open("mysql",url)
	db.SetMaxOpenConns(20)
	db.SetMaxIdleConns(10)
	db.Ping()
}
func execSQL(bus busStatus,stmt *sql.Stmt) {
	stmt.Exec(bus.SiteId,bus.BusID,bus.GpsMileage,bus.SiteName,bus.SiteNo,bus.BusPlate,bus.PlanRuns,bus.RoadName,bus.PlanTime,bus.RoadID,bus.GpsSpeed,bus.DateTime,bus.CompCode,bus.SiteState,bus.GpsDate,bus.GpsDirection,bus.RoadType,bus.BusState,bus.GpsCode,bus.CurrentRuns)
}
func initMap(){
	var rows, _ = db.Query("SELECT SiteId,BusId,GpsMileage,SiteName,SiteNo,BusPlate,PlanRuns,RoadName,PlanTime,RoadID,GpsSpeed,DateTime,CompCode,SiteState,GpsDate,GpsDirection,RoadType,BusState,GpsCode,CurrentRuns FROM BusState")
	for rows.Next()  {
		var bus busStatus
		err := rows.Scan(&bus.SiteId,&bus.BusID,&bus.GpsMileage,&bus.SiteName,&bus.SiteNo,&bus.BusPlate,&bus.PlanRuns,&bus.RoadName,&bus.PlanTime,&bus.RoadID,&bus.GpsSpeed,&bus.DateTime,&bus.CompCode,&bus.SiteState,&bus.GpsDate,&bus.GpsDirection,&bus.RoadType,&bus.BusState,&bus.GpsCode,&bus.CurrentRuns)
		if err != nil {
			fmt.Println(err)
		}else{
			buslist[bus.BusPlate] = bus.SiteName
		}

	}
	fmt.Println(len(buslist))
}
